#include<stdio.h>
#include<stdlib.h>
#include"../inc/LinkQueue.h"

LinkQueue *CreateQueue()
{
    LinkQueue *q=malloc(sizeof(LinkQueue));
    if (q==NULL)
    {
        return NULL;
    }
    q->front=NULL;
    q->rear=NULL;
    q->num=0;
    return q;
}

int EnQueue(LinkQueue *q,DataType data)
{
    if(q==NULL)
    {
        return 0;
    }
    NODE *newNode =(NODE *)malloc(sizeof(NODE));
    if(newNode==NULL)
    {
        return 0;
    }
    newNode->data=data;
    newNode->next=NULL;
    if (q->rear==NULL)//从无到有
    {
        q->front=newNode;
        q->rear=newNode;
    }
    else//从少到多
    {
        q->rear->next=newNode;
        q->rear=newNode;
    }
    q->num++;
    return 1;
}

int DeQueue(LinkQueue *q)
{
    if(q==NULL||q->front==NULL)
    {
        return 0;
    }
    NODE *temp=q->front;
    q->front = q->front->next;
    if(q->front==NULL)
    {
        q->rear=NULL;
    }
    free(temp);
    q->num--;
    return 1;
}

void DestroyQueue(LinkQueue *q) 
{
    if(q==NULL)
    {
        return;
    }
    for(NODE *p=q->front;p;)
    {
        NODE *p_last = p;
        p = p->next;
        free(p_last);
    }
    free(q);
}

void ClearQueue(LinkQueue *q)
{
    if(q==NULL)
    {
        return;
    }
    for(NODE *p=q->front;p;)
    {
        NODE *p_last = p;
        p = p->next;
        free(p_last);
    }
    q->front=NULL;
    q->rear=NULL;
    q->num=0;
}

int QueueLen(LinkQueue *q)
{
    if(q==NULL)
    {
        return 0;
    }
    return q->num;
}

DataType GetHead(LinkQueue *q)
{
    if(q==NULL||q->front==NULL)
    {
        return 0;
    }
    return q->front->data;
}

void PrintQueue(LinkQueue *q)
{
    if(q==NULL)
    {
        printf("Queue is Null!\n");
        return;
    }
    else if(q->front==NULL)
    {
        printf("Queue is empty!\n");
        return;
    }
    NODE *current=q->front;
    while(current != NULL)
    {
        printf("%c ",current->data);
        current=current->next;
    }
    printf("\n");
}
